package com.why.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author wanghongyang24
 */
@Service
public class WhyJsonRedisService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, String value) {
        this.noNull(key,value);
        stringRedisTemplate.opsForValue().set(key, value);
    }
    public String get(String key) {
        this.noNull(key);
        return stringRedisTemplate.opsForValue().get(key);
    }
    public void setExpire(String key, Long expire) {
        this.noNull(key,expire);
        stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }
    public void remove(String key) {
        this.noNull(key);
        stringRedisTemplate.delete(key);
    }
    public Long increment(String key, long delta) {
        this.noNull(key,delta);
        return stringRedisTemplate.opsForValue().increment(key,delta);
    }
    private void noNull(Object ...args){
        for (Object arg : args) {
                if(Objects.isNull(arg)){
                    throw new NullPointerException("redis 参数不能为空!");
                }else if(arg instanceof  String&& "".equals(arg)){
                    throw new NullPointerException("redis 参数不能为空字符串");
                }
        }
    }
}
